<?php
namespace app\service;

use app\exception\ErrnoPlus;
use app\model\SendTemplateModel;
use share\exception\ApiException;
use share\exception\Errno;
use share\service\BaseModelService;
use share\service\SendCodeService;
use share\utils\Helper;
use think\Log;

class SendTemplateService extends BaseModelService{

    CONST SEND_TYPE_OF_SMS = 1;
    CONST SEND_TYPE_OF_EMAIL = 2;

    
    CONST SEND_LANGUAGE_OF_CN = 1;
    CONST SEND_LANGUAGE_OF_EN = 2;


    public static function getModel()
    {
        return new SendTemplateModel();
    }

    public static function addTemplate($item)
    {
        $sendConfig = SendConfigService::getBase($item['send_config_id']);
        if(empty($sendConfig)){
            throw new ApiException("模版配置信息不存在",ErrnoPlus::COMMON_INVALID_INPUT);
        }

        if(intval($item['type']) !== $sendConfig['type']){
            throw new ApiException("模版配置信息发送类型不匹配",ErrnoPlus::COMMON_INVALID_INPUT);
        }
        return self::add($item);
    }

    public static function updateTemplate($id,$item)
    {
        $origin = self::getBase($id);
        if(!$origin){
            throw  new ApiException("data of id:{$id} is not exists! please check");
        }
        $sendConfig = SendConfigService::getBase($item['send_config_id']);
        if(empty($sendConfig)){
            throw new ApiException("模版配置信息不存在",ErrnoPlus::COMMON_INVALID_INPUT);
        }
        if(intval($item['type']) !== $sendConfig['type']){
            throw new ApiException("模版配置信息发送类型不匹配",ErrnoPlus::COMMON_INVALID_INPUT);
        }
        return  self::update($id,$item);
    }

    public static function setTemplate($param){
        $id =  $param['id'];
        unset($param['id']);
        if($id == 0){
            return self::addTemplate($param);
        }
        else{
            return self::updateTemplate($id,$param);
        }
    }

    /**
     * 默认短信模版
     */
    public static function defaultSendTemplate(){
        return [
            [
                'title' => 'ENZ',
                'no' => 'SMS_207665064',
                'type' => self::SEND_TYPE_OF_SMS,
                'scene' => SendCodeService::SEND_CODE_SCENE_VERIFY_CODE,
                'language' => self::SEND_LANGUAGE_OF_CN,
            ],
            [
                'title' => 'ENZ',
                'no' => 'SMS_259765538',
                'type' => self::SEND_TYPE_OF_SMS,
                'scene' => SendCodeService::SEND_CODE_SCENE_VERIFY_CODE,
                'language' => self::SEND_LANGUAGE_OF_EN,
            ],
            [
                'title' => '验证码',
                'no' => 'EMAIL_CN_VERIFY_CODE',
                'type' => self::SEND_TYPE_OF_EMAIL,
                'scene' => SendCodeService::SEND_CODE_SCENE_VERIFY_CODE,
                'language' => self::SEND_LANGUAGE_OF_CN,
            ],
            [
                'title' => 'verifyCode',
                'no' => 'EMAIL_EN_VERIFY_CODE',
                'type' => self::SEND_TYPE_OF_EMAIL,
                'scene' => SendCodeService::SEND_CODE_SCENE_VERIFY_CODE,
                'language' => self::SEND_LANGUAGE_OF_EN,
            ],
        ];
    }

    /**
     * 获取默认发送 配置
     * @param int $language 1 :cn  2:en 
     * @param int $type 1:SMS 2:EMAIL
     * @param string $scene 可用场景 如上
     * @return array|null
     */
    public static function getDefaultSendTemplate($language,$type,$scene){
        $allScene = self::getAllAllowScene($scene,$type);
        if(!in_array(SendCodeService::SEND_CODE_SCENE_VERIFY_CODE,$allScene)){
            trace("发送场景在 " .($type == self::SEND_TYPE_OF_EMAIL ? 'email' : 'sms')."-".$scene." 不存在默认配置",Log::ERROR);
            return null;
        }
        $defaultTemplates = self::defaultSendTemplate();
        $templateFilter = Helper::filterOne($defaultTemplates,[
            'language' => $language,
            'type' => $type,
        ]);
        $template = self::getByFilter($templateFilter);
        if(empty($template)){
            throw new ApiException("发送邮件/短信时.默认配置不存在或者已被删除 config:".json_encode($templateFilter),Errno::COMMON_SYSTEM_CONFIG_NOT_SET);
            return null;
        }
        return self::makeFullInfoByTemplate($template);
    }

    /**
     * @param array $ids
     * @param int $language 1 :cn  2:en 
     * @param int $type 1:SMS 2:EMAIL
     * @param string $scene 可用场景 如上
     * @return array|null
     */
    public static function getSendTemplate($ids,$language,$type,$scene){
        if(count($ids) < 1){
            return null;
        }
        $templates = self::getAllByFilter([
            'id' => ['in',$ids],
            'language' => $language,
            'type' => $type,
        ]);
        if(empty($templates)){
            return null;
        }
        $template = Helper::filterOne($templates,['scene' => $scene]);
        if($template){
            return self::makeFullInfoByTemplate($template);
        }
        $allAllowScene = self::getAllAllowScene($scene,$type);
        foreach($templates as $template){
            if(in_array($template['scene'],$allAllowScene)){
                return self::makeFullInfoByTemplate($template);
            }
        }
        return null;
    }

    /**
     * @param string $scene 可用场景 如上
     * @param int $type 1:SMS 2:EMAIL
     * @return array
     */
    public static function getAllAllowScene($scene,$type){
        $res = [$scene];
        if($type == self::SEND_TYPE_OF_SMS){
            if ($scene == SendCodeService::SEND_CODE_SCENE_LOGIN 
                || $scene == SendCodeService::SEND_CODE_SCENE_REGISTER 
                || $scene == SendCodeService::SEND_CODE_SCENE_RESET_PASS 
                || $scene == SendCodeService::SEND_CODE_SCENE_DEVICE_PASS
                || $scene == SendCodeService::SEND_CODE_SCENE_TRANSFER_DEVICE
                ) {
                array_push($res,SendCodeService::SEND_CODE_SCENE_VERIFY_CODE);
            }
            if ($scene == SendCodeService::SEND_CODE_SCENE_USER_RECEIVED) {
                array_push($res,SendCodeService::SEND_CODE_SCENE_USER_RECEIVED);
            }
        }
        else{
            if (
                $scene == SendCodeService::SEND_CODE_SCENE_LOGIN 
                || $scene == SendCodeService::SEND_CODE_SCENE_REGISTER 
                || $scene == SendCodeService::SEND_CODE_SCENE_RESET_PASS
                || $scene == SendCodeService::SEND_CODE_SCENE_TRANSFER_DEVICE
                ) {
                array_push($res,SendCodeService::SEND_CODE_SCENE_VERIFY_CODE);
            }
            if ($scene == SendCodeService::SEND_CODE_SCENE_DEVICE_PASS) {
                array_push($res,SendCodeService::SEND_CODE_SCENE_DEVICE_PASS);
            }
            if ($scene == SendCodeService::SEND_CODE_SCENE_USER_CHANGE) {
                array_push($res,SendCodeService::SEND_CODE_SCENE_USER_CHANGE);
            }
            if ($scene == SendCodeService::SEND_CODE_SCENE_USER_RECEIVED) {
                array_push($res,SendCodeService::SEND_CODE_SCENE_USER_RECEIVED);
            }
        }
        return $res;
    }

    /**
     * 
     */
    public static function makeFullInfoByTemplate($template){
        if(empty($template)){
            return null;
        }
        $config = SendConfigService::getBase($template['send_config_id']);
        if(empty($config)){
            throw new ApiException("发送的密钥信息已被删除 template:".json_encode($template),Errno::COMMON_SYSTEM_CONFIG_NOT_SET);
        }
        $content = SendTemplateContentService::getByFilter(['no' => $template['no']]);
        if($template['type'] == self::SEND_TYPE_OF_EMAIL && empty($content)){
            throw new ApiException("模版内容未配置.或者已被删除 template:".json_encode($template),Errno::COMMON_SYSTEM_CONFIG_NOT_SET);
        }
        if($config['ext']){
            $config['ext'] = @json_decode($config['ext'],true);
        }
        else{
            $config['ext'] = [];
        }
        $template = array_merge($template,[
            'config_name' => $config['name'],
            'appid' => $config['appid'],
            'app_sceret' => $config['app_sceret'],
            'config_ext' => $config['ext'],
        ]);
        if($content){
            $template = array_merge($template,[
                'content' => $content['content'],
                'params' => $content['params'],
            ]);
        }
        return $template;
    }

    public static function buildCondition($filter)
    {
        $res = [];
        if(isset($filter['title']) && !empty($filter['title'])){
            $res['title'] = ['like','%'.$filter['title'].'%'];
        }
        if(isset($filter['no']) && !empty($filter['no'])){
            $res['no'] = ['like','%'.$filter['no'].'%'];
        }
        if(isset($filter['name']) && !empty($filter['name'])){
            $res['name'] = ['like','%'.$filter['name'].'%'];
        }
        if(isset($filter['type']) && !empty($filter['type'])){
            $res['type'] = $filter['type'];
        }
        if(isset($filter['scene']) && !empty($filter['scene'])){
            $res['scene'] = $filter['scene'];
        }
        if(isset($filter['language']) && !empty($filter['language'])){
            $res['language'] = $filter['language'];
        }
        return $res;
    }
}